﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Collections.Generic;

using SBPweb.Forge.Contracts.Events;

using SBPweb.PROvibe.Business.Shared.Contracts.Content;

using SBPweb.PROvibe.Business.Client.Library.Modularity;

namespace SBPweb.PROvibe.Business.Client.Library.Content
{

    public static class ContentManager
    {

        #region Private fields

        private static Dictionary<ContainerDescriptor, IContainer> dictContainers = new Dictionary<ContainerDescriptor, IContainer>();

        #endregion

        #region Constructor logic

        static ContentManager()
        {
            ModuleLoader.AddInstanceCreatedHandler<IContainer>(new EventHandler<ModuleLoaderObjectCreatedEventArgs<IContainer>>(OnModuleLoaderContainerItemCreated));
            ModuleLoader.AddInstanceCreatedHandler<Control>(new EventHandler<ModuleLoaderObjectCreatedEventArgs<Control>>(OnModuleLoaderControlItemCreated));
        }

        #endregion

        #region Methods

        public static void RegisterContainer(ContainerDescriptor containerId, IContainer container)
        {
            dictContainers.Add(containerId, container);
        }

        private static void OnModuleLoaderContainerItemCreated(object sender, ModuleLoaderObjectCreatedEventArgs<IContainer> e)
        {
            foreach (ContainerDescriptor key in e.Object.Containers)
            {
                RegisterContainer(key, e.Object);
            }
        }

        private static void OnModuleLoaderControlItemCreated(object sender, ModuleLoaderObjectCreatedEventArgs<Control> e)
        {
            ContentItemDescriptor cId = e.UserState as ContentItemDescriptor;
            if (cId == null)
            {
                return;
            }
            ContainerDescriptor tCId = cId.TargetContainer;
            if (dictContainers.ContainsKey(tCId))
            {
                IContainer iC = dictContainers[tCId] as IContainer;
                if (!dictContainers.ContainsKey(tCId))
                {
                    return;
                }
                iC.AssignContainerContent(tCId, e.Object);
            }
        }
        
        #endregion

    }

}